<?php

namespace App\Http\Controllers\H5;

use App\Library\User\PointManager;
use App\Models\User;
use Illuminate\Http\Request;


class GameController extends BaseController
{
    public function index()
    {
        $treeCount = $this->user()->trees()->count();
        $energy = $this->user()->trees()->sum('energy');
        $wallet = $this->user()->wallet()->firstOrCreate([]);
        return $this->view('h5.game.index', compact('wallet', 'treeCount', 'energy'));
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function point()
    {
        $wallet = $this->user()->wallet()->firstOrCreate([]);
        return $this->view('h5.game.point', compact('wallet'));
    }

    public function getBubbles(Request $request)
    {
        $items = $this->user()->bubbles()->get()->map(function ($bubble){
            return $bubble;
        });

        return ajaxReturn(['items'=>$items]);
    }

    public function pickupBubble(Request $request)
    {
        $id = $request->input('id');
        $bubble = $this->user()->bubbles()->find($id);
        if ($bubble)
        {
            PointManager::addPoints($this->user, $bubble->points, 'bubble', '点击茶园气泡获得积分', 1);
            $tree = $bubble->tree;
            $tree->bubbles_picked+= $bubble->points;
            $tree->save();
            $bubble->delete();
        }
        return ajaxReturn();
    }

    public function getRecords(Request $request)
    {
        $items = $this->user()->pointRecords()->where('type', 1)
            ->orderByDesc('id')->get()->map(function ($item){
                $item->created_at = @date('Y-m-d H:i:s', $item->created_at);
                return $item;
            });

        return ajaxReturn(['items'=>$items]);
    }

    public function transfer(Request $request)
    {
        $transfer = $request->input('transfer');
        $user = User::where('mobile', $transfer['mobile'])->first();
        if ($user)
        {
            if ($this->user()->jypassword != md5($transfer['jypass']))
            {
                return ajaxError(2, '交易密码错误');
            }

            $transfer['points'] = intval($transfer['points']);
            if ($transfer['points'] <= 0)
            {
                return ajaxError(3, '赠送积分不能小于0');
            }

            $wallet = $this->user->wallet;
            if ($wallet['points'] < $transfer['points'])
            {
                return ajaxError(3, '茶多分余额不足');
            }

            PointManager::addPoints($user, $transfer['points'], 'transfer', '好友赠送积分', 1);
            PointManager::takeOffPoints($this->user, $transfer['points'], 'transfer', '赠送好友积分', 1);

            return ajaxReturn();

        } else {
            return ajaxError(1, '对方账号不存在');
        }
    }
}
